<template>
  <div class="cateManager">
    <!-- 头部 -->
    <hmheader title="栏目管理">
      <template #left>
        <van-icon name="arrow-left" @click="$router.go(-1)" />
      </template>
    </hmheader>
    <!-- 主体 -->
    <div class="delcate">
      <h3>点击删除频道</h3>
      <div class="list">
        <span
          v-for="value in cateList"
          :key="value.id"
          @click="removeCate(value)"
          >{{ value.name }}</span
        >
      </div>
    </div>
    <div class="addcate">
      <h3>点击添加频道</h3>
      <div class="list">
        <span
          v-for="value in unaddCateList"
          :key="value.id"
          @click="addCate(value)"
          >{{ value.name }}</span
        >
      </div>
    </div>
  </div>
</template>

<script>
import hmheader from "@/components/hmheader.vue";
import { getCateList } from "@/apis/category.js";
export default {
  components: {
    hmheader,
  },
  data() {
    return {
      // 已添加栏目
      cateList: [],
      //   未添加栏目
      unaddCateList: [],
    };
  },
  //   页面一家加载就获取栏目所有数据
  async mounted() {
    //   先读取本存储数据，如果没有数据，才会向后台服务器发起数据请求
    this.cateList = JSON.parse(localStorage.getItem("cateList") || "[]");
    if (this.cateList.length == 0) {
      let res = await getCateList();
      //   console.log(res);
      this.cateList = res.data.data;
      // 去掉头条和关注
      if (localStorage.getItem("heimatoutiao_token")) {
        this.cateList.splice(0, 2);
      } else {
        this.cateList.splice(0, 1);
      }
      console.log(this.cateList);
    }
    this.unaddCateList = JSON.parse(
      localStorage.getItem("unaddCateList") || "[]"
    );
  },
  methods: {
    removeCate(value) {
      //   1.将当前栏目添加到“未添加”栏目
      this.unaddCateList.push(value);
      // 2.将当前栏目从“已添加栏目”移出
      this.cateList = this.cateList.filter((v) => {
        return v.id != value.id;
      });
      //   将两个数组存储到本地存储，本地存储只能存储字符串
      localStorage.setItem("cateList", JSON.stringify(this.cateList));
      localStorage.setItem("unaddCateList", JSON.stringify(this.unaddCateList));
    },
    addCate(value) {
      //   1.将当前栏目添加到“已添加”栏目
      this.cateList.push(value);
      // 2.将当前栏目从“未添加栏目”移出
      this.unaddCateList = this.unaddCateList.filter((v) => {
        return v.id != value.id;
      });
      //   将两个数组存储到本地存储，本地存储只能存储字符串
      localStorage.setItem("cateList", JSON.stringify(this.cateList));
      localStorage.setItem("unaddCateList", JSON.stringify(this.unaddCateList));
    },
  },
};
</script>

<style lang="less" scoped>
.delcate,
.addcate {
  padding: 10px;
  h3 {
    line-height: 30px;
    font-weight: bold;
  }
  .list {
    display: flex;
    flex-wrap: wrap;
    span {
      width: 22%;
      border: 1px solid #ccc;
      background-color: #fff;
      margin: 5px;
      padding: 10px;
      text-align: center;
    }
  }
}
</style>